import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import TreeSelector from '@/components/TreeSelector';
import { useRequest } from '@/hooks';
import { message } from 'antd';
import { HighlightText } from '@/molecules';
import IconFont from '@/components/IconFont';
import { fetchDutyListByOrganizationCode } from '@/services/organization';
import { preprocessDataItem } from './util';

const parseData = data => {
    const result = [];
    data.forEach(item => {
        const newItem = {
            ...item,
            id: item.organizationPath,
            pId: item.parentOrganizationPath,
            title: item.organizationName,
            selectable: false,
            isLeaf: false,
            hasDataPermission: item.organizationPermissions !== 0
        };
        if (newItem.duties?.length) {
            newItem.duties.forEach(duty => {
                result.push({
                    ...duty,
                    id: duty.dutyCode,
                    title: duty.dutyAlias,
                    pId: newItem.organizationPath,
                    selectable: false,
                    isLeaf: true,
                    hasDataPermission: newItem.organizationPermissions !== 0
                });
            });
        }
        result.push(newItem);
    });
    return result;
};

export const useFetchDutyData = config => {
    const { param = {}, useCache = true, ...otherProps } = config || {};
    const cacheConfig = useCache
        ? {
              cacheKey: `duty-data-${Object.values(param || {}).join('-')}`,
              staleTime: 60000 // 1分钟
          }
        : {};
    return useRequest(() => fetchDutyListByOrganizationCode({ showTreeFlag: 0, ...param }), {
        ...cacheConfig,
        ready: param?.organizationCode,
        refreshDeps: [param?.organizationCode],
        formatResult: res => {
            if (res) {
                const { code, msg } = res;
                if (code === 10000) {
                    return parseData(res.data);
                }
                message.error(msg);
            }
            return undefined;
        },
        ...otherProps
    });
};

// 自定义渲染节点
const renderTreeNodeTitle = (node, keyword) => {
    const title =
        node.auditStatus.toString() !== '2' && node.disabled ? (
            `${node.title}(审批中)`
        ) : (
            <HighlightText keywords={keyword}>{node.title}</HighlightText>
        );
    if (node?.isLeaf === false) {
        return (
            <>
                <IconFont
                    icon="iconzuzhijiagouICON"
                    style={{ fontSize: 16, marginRight: 4, color: 'rgba(0,0,0,0.15)', verticalAlign: -1 }}
                />
                {title}
                {node.statistics !== null && node.statistics !== undefined ? `(${node.statistics})` : ''}
            </>
        );
    }
    return title;
};

/**
 * 岗位选择组件
 */
const DutySelector = React.forwardRef((props, ref) => {
    const {
        data: outerData,
        loading: outerLoading,
        organizationCode,
        treeCheckStrictly,
        isNeedPermission,
        isDeleteInvalidNode,
        isDisableAuditData,
        isStatisticsChildren,
        isIgnoreOptionDisabled,
        ...otherProps
    } = props;
    // 获取数据
    const { data = outerData, loading } = useFetchDutyData({
        ready: !outerData,
        param: {
            organizationCode,
            dutyPermissionFlag: isNeedPermission ? 1 : 0
        }
    });
    const processedData = useMemo(
        () =>
            preprocessDataItem(data, {
                isNeedPermission,
                isDeleteInvalidNode,
                isDisableAuditData,
                isIgnoreOptionDisabled,
                isStatisticsChildren,
                treeCheckStrictly
            }) || [],
        [
            data,
            isDeleteInvalidNode,
            isDisableAuditData,
            isIgnoreOptionDisabled,
            isNeedPermission,
            isStatisticsChildren,
            treeCheckStrictly
        ]
    );
    return (
        <TreeSelector
            ref={ref}
            data={processedData}
            loading={outerLoading ?? loading}
            renderTreeNodeTitle={renderTreeNodeTitle}
            treeCheckStrictly={treeCheckStrictly}
            {...otherProps}
        />
    );
});

DutySelector.propTypes = {
    /** placeholder */
    placeholder: PropTypes.string,
    /** 是否禁用组件 */
    disabled: PropTypes.bool,
    /** 不渲染触发器, 编码方式控制弹框展示 */
    manual: PropTypes.bool,
    /** 可选的最大数量, multiple: true 情况下可用 */
    max: PropTypes.oneOfType([PropTypes.number, PropTypes.bool]),
    /** 是否使用弹框的交互形式 */
    modal: PropTypes.bool,
    /** 是否是多选 */
    multiple: PropTypes.bool,
    /** 树节点选择策略是否是严格模式, 默认是 false. multiple: true 情况下可用 */
    treeCheckStrictly: PropTypes.bool,
    /** 结果预览是否开启分组展示. multiple: true 情况下可用 */
    isPreviewByGroup: PropTypes.bool,
    /** 结果的排序, 默认是 desc. multiple: true 情况下可用 */
    previewSortType: PropTypes.oneOf(['asc', 'desc']),
    /** 指定机构编码 */
    organizationCode: PropTypes.string,
    /** 是否删除无效的节点 */
    isDeleteInvalidNode: PropTypes.bool,
    /** 是否禁用审批中的数据, 默认为 false */
    isDisableAuditData: PropTypes.bool,
    /** 是否取消节点的禁用状态 */
    isIgnoreOptionDisabled: PropTypes.bool,
    /** 是否需要数据权限, 默认为 false. (权限与用户和模块相关, 新的业务需要申请数据权限, 可以联系公共服务组的服务端的伙伴配置) */
    isNeedPermission: PropTypes.bool,
    /** 是否统计子节点, 默认为 false */
    isStatisticsChildren: PropTypes.bool
};
DutySelector.defaultProps = {
    placeholder: '请选择岗位',
    disabled: false,
    manual: false,
    max: false,
    modal: false,
    multiple: false,
    isDisableAuditData: false,
    isDeleteInvalidNode: false,
    isIgnoreOptionDisabled: false,
    isNeedPermission: false,
    isStatisticsChildren: false,
    treeCheckStrictly: false,
    isPreviewByGroup: false,
    previewSortType: 'desc',
    organizationCode: null
};
DutySelector.displayName = 'DutySelector';

export default DutySelector;
